package com.bbcare.nutritious.plat.service.imp;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateTimeUtil;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import com.bbcare.nutritious.plat.entity.NtCourseFood;
import com.bbcare.nutritious.plat.entity.NtCourseNutrients;
import com.bbcare.nutritious.plat.entity.NtCoursePeriodtime;
import com.bbcare.nutritious.plat.entity.NtSchemeCourseVersion;
import com.bbcare.nutritious.plat.entity.NtSchemeStage;
import com.bbcare.nutritious.plat.entity.NtSchemeVersion;
import com.bbcare.nutritious.plat.entity.NtStageCourse;
import com.bbcare.nutritious.plat.entity.PtCourseSituation;
import com.bbcare.nutritious.plat.entity.PtNtcourseFood;
import com.bbcare.nutritious.plat.entity.PtNtcourseNutrients;
import com.bbcare.nutritious.plat.entity.PtNtcoursePeriodtime;
import com.bbcare.nutritious.plat.entity.PtNtschemeCourse;
import com.bbcare.nutritious.plat.entity.PtNtschemeInfo;
import com.bbcare.nutritious.plat.entity.PtNtschemeStage;
import com.bbcare.nutritious.plat.entity.PtNtsituationModifyLog;
import com.bbcare.nutritious.plat.service.INutritionSchemeService;
import com.bbcare.nutritious.plat.store.ibatis.INutritionSchemeUsedDao;
import com.bbcare.nutritious.plat.store.ibatis.IWeightDao;

/**
 *
 * @name:         NutritionSchemeUsedService.java
 * @author:       tao
 * @createTime:   2017年7月3日
 * @description:  营养方案使用服务类
 * @modify:
 *
 */
@Service
public class NutritionSchemeService implements INutritionSchemeService {

	public static final Logger logger = Logger.getLogger(NutritionSchemeService.class);

    @Autowired
    private INutritionSchemeUsedDao iNutritionSchemeUsedDao;

    @Resource(name = "jedisPool")
	private JedisPool jedisPool;

    @Autowired
    private IPatientDAO patientDao;

    @Autowired
    private IFollowQueueService fllowQueueService;
    @Autowired
    private IWeightDao weightDao;

	@Override
	@Transactional
	public Map<String, Object> patientSchemeUsed(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeUsed");
		Map<String,Object> rspMap = new HashMap<String,Object>();

		String createAuthor = (String)map.get("authorId");
		String schemeVersionId = (String)map.get("schemeVersionId");
		String userId = (String)map.get("userId");
		String tenantId = (String)map.get("tenantId");
		String currenTime = DateUtil.getSysDateA();

		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		paramMap.put("tenantId", tenantId);
		Patient patient = patientDao.selectById(map);
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
		}

		// 患者当前已经有启用的营养方案  停止
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		List<PtNtschemeInfo> schmeInfos = iNutritionSchemeUsedDao.selectPatientSchemeInfoUsed(paramMap);
		if(!CollectionUtils.isEmpty(schmeInfos)){
			PtNtschemeInfo schmeInfo = schmeInfos.get(0);
			paramMap.clear();
			paramMap.put("ptSchemeId",schmeInfo.getId());
			paramMap.putAll(map);
			this.patientSchemeStop(paramMap);
		}

		paramMap.clear();
		paramMap.put("schemeVersionId",schemeVersionId);
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		NtSchemeVersion version = iNutritionSchemeUsedDao.selectSchemeVersionDetail(paramMap);
		if(null == version){
			throw new AppException(ErrorCode.NUTRITION_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,"方案信息不存在");
		}

		//构建方案版本信息
		PtNtschemeInfo ptScheme= new PtNtschemeInfo();
		ptScheme.setId(SeqUtil.getSeqNo());
		ptScheme.setCreateAuthor(createAuthor);
		ptScheme.setCreateTime(currenTime);
		ptScheme.setStatus(Constants.COMMON_STATUS_NOMAL); //正常
		ptScheme.setTenantId(tenantId);
		ptScheme.setPschmeName(version.getVersionName());
		ptScheme.setUserId(userId);
		ptScheme.setSchemeDesc(version.getVersionDesc());
		ptScheme.setSchemeversionId(version.getId());
		iNutritionSchemeUsedDao.savePatientScheme(ptScheme);
		rspMap.put("ptNtschemeId",ptScheme.getId());

		//根据id查询方案阶段
		Map<String,Object> stageParam = new HashMap<String, Object>();
		stageParam.put("schemeVersionId",schemeVersionId);
		stageParam.put("status",Constants.COMMON_STATUS_NOMAL);
		List<NtSchemeStage> stageList = iNutritionSchemeUsedDao.selectSchemeStageList(stageParam);

		List<PtNtschemeStage> ptStageList = new ArrayList<PtNtschemeStage>();
		List<PtNtschemeCourse> ptCourselist = new ArrayList<PtNtschemeCourse>();
		List<PtNtcourseFood> ptCourseFoodlist = new ArrayList<PtNtcourseFood>();
		List<PtCourseSituation> ptCourseSituationlist = new ArrayList<PtCourseSituation>();
		List<PtNtcoursePeriodtime> ptCoursePeriodlist = new ArrayList<PtNtcoursePeriodtime>();
		List<PtNtcourseNutrients> ptCourseNutrientlist = new ArrayList<PtNtcourseNutrients>();

		PtNtschemeStage ptSchemeStage = null;
		if(!CollectionUtils.isEmpty(stageList)){
			for(int i =0;i<stageList.size();i++){
				String stageId = stageList.get(i).getId();

				ptSchemeStage = new PtNtschemeStage();
				ptSchemeStage.setId(SeqUtil.getSeqNo());
				ptSchemeStage.setCreateAuthor(createAuthor);
				ptSchemeStage.setCreateTime(currenTime);
				ptSchemeStage.setId(SeqUtil.getSeqNo());
				ptSchemeStage.setPschemeId(ptScheme.getId());
				ptSchemeStage.setStageName(stageList.get(i).getStageName());
				ptSchemeStage.setStageNo(stageList.get(i).getStageNo());
				ptSchemeStage.setStatus(Constants.COMMON_STATUS_NOMAL);

				ptStageList.add(ptSchemeStage);

				//查询入参map
				paramMap.clear();
				stageParam.put("stageId", stageId);
				stageParam.put("status",Constants.COMMON_STATUS_NOMAL);
				List<NtStageCourse> stageCourses = iNutritionSchemeUsedDao.selectStageCourseList(stageParam);
				if(!CollectionUtils.isEmpty(stageCourses)){
//					courselist = new ArrayList<NtSchemeCourseVersion>();
					PtNtschemeCourse ptCourse = null;
					for(int j = 0 ; j <stageCourses.size();j++){
						String courseVersionId = stageCourses.get(j).getCourseversionId();
						int pcourseNo  =stageCourses.get(j).getCourseNo();
						//根据疗程id 疗程基本信息
						stageParam.put("courseVersionId", courseVersionId);
						stageParam.put("status",Constants.COMMON_STATUS_NOMAL);
					  	NtSchemeCourseVersion  coure = iNutritionSchemeUsedDao.selectCourseVersionDetail(stageParam);
					  	if(null == coure){
							//疗程已经被删除
					  		continue;
					  	}
						ptCourse = new PtNtschemeCourse();
						ptCourse.setId(SeqUtil.getSeqNo());
						ptCourse.setCourseName(coure.getCourseName());
						ptCourse.setCourseversionId(courseVersionId);
						ptCourse.setCreateAuthor(createAuthor);
						ptCourse.setCreateTime(currenTime);
						ptCourse.setPschemeId(ptScheme.getId());
						ptCourse.setPstageId(ptSchemeStage.getId());
						ptCourse.setUserId(userId);
						ptCourse.setTenantId(tenantId);
						ptCourse.setCourseTotal(coure.getCourseTotal());
						ptCourse.setPcourseNo(pcourseNo);
						ptCourse.setStatus(Constants.COMMON_STATUS_NOMAL);
						ptCourselist.add(ptCourse);

						//疗程标准
						List<NtCourseNutrients> courseNutrientList = iNutritionSchemeUsedDao.selectCourseNutrientsPublish(paramMap);
						if(!CollectionUtils.isEmpty(courseNutrientList)){
							PtNtcourseNutrients courseNutrient = null;
							for(int k = 0;k<courseNutrientList.size();k++){
								courseNutrient = new PtNtcourseNutrients();
								courseNutrient.setId(SeqUtil.getSeqNo());
								courseNutrient.setActualAmount(courseNutrientList.get(k).getActualAmount());
								courseNutrient.setAverageAmount(courseNutrientList.get(k).getAverageAmount());
								courseNutrient.setCreateAuthor(createAuthor);
								courseNutrient.setCreateTime(currenTime);
								courseNutrient.setMaxAmount(courseNutrientList.get(k).getMaxAmount());
								courseNutrient.setMinAmount(courseNutrientList.get(k).getMinAmount());
								courseNutrient.setPcourseId(ptCourse.getId());
								courseNutrient.setNutrientCode(courseNutrientList.get(k).getNutrientsCode());
								courseNutrient.setNutrientsId(courseNutrientList.get(k).getNutrientsId());
								courseNutrient.setRemark(courseNutrientList.get(k).getRemark());
								ptCourseNutrientlist.add(courseNutrient);
							}
						}

						paramMap.clear();
						paramMap.put("courseVersionId",courseVersionId);
						paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
						PtNtcoursePeriodtime periodTime = null;
						List<NtCoursePeriodtime> periodList =  iNutritionSchemeUsedDao.selectCoursePeriods(paramMap);
						//应用时间段ID和疗程库时间段对应关系
						Map<String,String> periodMap = new HashMap<String,String>();
						if(!CollectionUtils.isEmpty(periodList)){
							for(int k =0;k<periodList.size();k++){
								periodTime = new PtNtcoursePeriodtime();
								periodTime.setId(SeqUtil.getSeqNo());
								periodTime.setCreateAuthor(createAuthor);
								periodTime.setCreateTime(currenTime);
								periodTime.setEndTime((String)periodList.get(k).getEndTime());
								periodTime.setStartTime((String)periodList.get(k).getStartTime());
								periodTime.setPcourseId(ptCourse.getId());
								periodTime.setPeriodName((String)periodList.get(k).getPeriodName());
								periodTime.setTenantId(tenantId);
								ptCoursePeriodlist.add(periodTime);

								String periodId = (String)periodList.get(k).getId();
								periodMap.put(periodId, periodTime.getId());
							}
							//每个阶段下的食物列表
							paramMap.clear();
							paramMap.put("courseVersionId",courseVersionId);
							paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
							//饮食情况列表
							PtNtcourseFood ptNtcourseFood = null;
							List<NtCourseFood> courseFoodList = iNutritionSchemeUsedDao.selectCourseFoods(paramMap);

							PtCourseSituation ptCourseSituation=null;
							if(!CollectionUtils.isEmpty(courseFoodList)){
								for(int l=0;l<courseFoodList.size();l++){
									ptNtcourseFood = new PtNtcourseFood();
									ptNtcourseFood.setId(SeqUtil.getSeqNo());
									ptNtcourseFood.setCreateAuthor(createAuthor);
									ptNtcourseFood.setCreateTime(currenTime);
									ptNtcourseFood.setFoodId(courseFoodList.get(l).getFoodId());
									ptNtcourseFood.setPcourseId(ptCourse.getId());
									ptNtcourseFood.setStatus(Constants.COMMON_STATUS_NOMAL);
									ptNtcourseFood.setTotal(courseFoodList.get(l).getTotal());
									ptNtcourseFood.setPeriodId(periodMap.get(courseFoodList.get(l).getPeriodId()));
									ptCourseFoodlist.add(ptNtcourseFood);

									for(int m = 0 ;m<ptCourse.getCourseTotal();m++){
										ptCourseSituation = new PtCourseSituation();
										ptCourseSituation.setId(SeqUtil.getSeqNo());
										ptCourseSituation.setDay(m+1);
										ptCourseSituation.setCreateTime(currenTime);
										ptCourseSituation.setDefaultAmount(courseFoodList.get(l).getTotal());
										ptCourseSituation.setFoodId(courseFoodList.get(l).getFoodId());
										ptCourseSituation.setPcourseId(ptCourse.getId());
										ptCourseSituation.setPeriodId(periodMap.get(courseFoodList.get(l).getPeriodId()));
										ptCourseSituation.setPschemeId(ptScheme.getId());
										ptCourseSituation.setStatus(Constants.COMMON_STATUS_NOMAL);
										ptCourseSituation.setUserId(userId);
										ptCourseSituation.setTenantId(tenantId);
										ptCourseSituationlist.add(ptCourseSituation);
									}
								}
							}
						}
					}
				}
			}
		}else{
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_NUTRITION_STAGE_NOT_EXISTS,"方案没有配置阶段");
		}

		if(!CollectionUtils.isEmpty(ptStageList)){
			iNutritionSchemeUsedDao.savePatientStages(ptStageList);
		}
		if(!CollectionUtils.isEmpty(ptCourselist)){
			iNutritionSchemeUsedDao.savePatientCourse(ptCourselist);
		}
		if(!CollectionUtils.isEmpty(ptCoursePeriodlist)){
			iNutritionSchemeUsedDao.savePatientPeriod(ptCoursePeriodlist);
		}
		if(!CollectionUtils.isEmpty(ptCourseFoodlist)){
			iNutritionSchemeUsedDao.savePatientCourseFood(ptCourseFoodlist);
		}
		if(!CollectionUtils.isEmpty(ptCourseSituationlist)){
			iNutritionSchemeUsedDao.savePatientSituation(ptCourseSituationlist);
		}
		if(!CollectionUtils.isEmpty(ptCourseNutrientlist)){
			iNutritionSchemeUsedDao.savePatientCourseNutrients(ptCourseNutrientlist);
		}

		return rspMap;
	}

	@Override
	public Map<String, Object> patientSchemeDetail(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeDetail");
		Map<String,Object> rspMap = new HashMap<String,Object>();
		String userId = (String)map.get("userId");
		String tenantId = (String)map.get("tenantId");
		String ptSchemeId = (String)map.get("ptSchemeId");

		//查询用户是否存在
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("tenantId",tenantId);
		paramMap.put("userId",userId);
		Patient patient = patientDao.selectById(paramMap);
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
		}

		List<Map<String,Object>> dataStages = new ArrayList<Map<String,Object>>();//返回方案下阶段内容列表
		List<Map<String,Object>> dataCourses = null;//返回阶段下的疗程列表

		//查询方案阶段列表
		paramMap.put("ptSchemeId",ptSchemeId);
//		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);//终止也可查询
		List<PtNtschemeInfo> ptNtschemes = iNutritionSchemeUsedDao.selectPatientSchemeInfo(paramMap);
		//查询应用方案信息

		if(CollectionUtils.isEmpty(ptNtschemes)){
			throw new AppException(ErrorCode.NUTRITION_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,"患者方案信息不存在");
		}
		PtNtschemeInfo ptNtscheme = ptNtschemes.get(0);
		rspMap.put("ptSchemeName", ptNtscheme.getPschmeName());
		rspMap.put("ptSchemeDesc",ptNtscheme.getSchemeDesc());
		rspMap.put("userId",patient.getId());
		rspMap.put("userName",patient.getUserName());
		rspMap.put("birthday",patient.getBirthday());
		rspMap.put("pregnancyDay",patient.getPregnancyDay());
		rspMap.put("status", ptNtscheme.getStatus());
		Long birthLong=ToolUtils.getCorrect(patient.getBirthday(),patient.getPregnancyDay());//生日时间戳
		String age = ToolUtils.getCommAgeByBirthday(DateUtil.getDate_8(new Date()),DateUtil.getDate_8(new Date(birthLong)));
		rspMap.put("age",age);

		//查询阶段疗程列表
		List<PtNtschemeStage> stagesList = iNutritionSchemeUsedDao.selectPatientStageList(paramMap);
		if(!CollectionUtils.isEmpty(stagesList)){
			Map<String,Object> stageMap = null;
			for(int i = 0 ;i<stagesList.size();i++){
				stageMap = new HashMap<String,Object>();
				stageMap.put("ptStageName",stagesList.get(i).getStageName());
				stageMap.put("ptStageId",stagesList.get(i).getId());
				stageMap.put("ptStageNo",stagesList.get(i).getStageNo());
				stageMap.put("remark",stagesList.get(i).getRemark());
				stageMap.put("status",stagesList.get(i).getStatus());
				paramMap.clear();
				paramMap.put("ptSchemeId",ptSchemeId);
				paramMap.put("ptStageId",stagesList.get(i).getId());
				List<PtNtschemeCourse> ptcourselist = iNutritionSchemeUsedDao.selectPatientCourseList(paramMap);
				dataCourses =  new ArrayList<Map<String,Object>>();
				if(!CollectionUtils.isEmpty(ptcourselist)){
					Map<String,Object> courseMap = null;
					for(int j=0;j<ptcourselist.size();j++){
						courseMap = new HashMap<String,Object>();
						courseMap.put("courseVersionId",ptcourselist.get(j).getCourseversionId());
						courseMap.put("ptCourseId",ptcourselist.get(j).getId());
						courseMap.put("ptCourseName",ptcourselist.get(j).getCourseName());
						courseMap.put("ptCourseNo",ptcourselist.get(j).getPcourseNo());
						courseMap.put("remark",ptcourselist.get(j).getRemark());
						courseMap.put("pStageId",ptcourselist.get(j).getPstageId());
						courseMap.put("status",ptcourselist.get(j).getStatus());
						dataCourses.add(courseMap);
					}
				}
				stageMap.put("ptCourses", dataCourses);
				dataStages.add(stageMap);
			}
		}
		rspMap.put("ptStages",dataStages);

		return rspMap;
	}

	@Override
	public Map<String, Object> patientCourseDetail(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeDetail");
		Map<String,Object> rspMap = new HashMap<String,Object>();

		List<Map<String,Object>> dataSituations = new ArrayList<Map<String,Object>>(); //返回每天饮食情况列表
//		List<Map<String,Object>> periodHeads= new ArrayList<Map<String,Object>>();//返回疗程 餐次时段 和 每个餐次食物

		String patientCourseId =  (String)map.get("ptCourseId");

		//查询用户是否存在
		Map<String,Object> paramMap = new HashMap<String, Object>();
		paramMap.put("ptCourseId",patientCourseId);
		PtNtschemeCourse ptNtschemeCourse = iNutritionSchemeUsedDao.selectPatientCourseInfo(paramMap);
		if(null == ptNtschemeCourse){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_NUTRITION_COURSEVERSION_NOT_EXISTS_ERROR,"患者疗程信息不存在");
		}

		List<Map<String,Object>> periodFoodList = iNutritionSchemeUsedDao.selectPatientPeriodFoodList(paramMap);

		List<Map<String,Object>> periodList = iNutritionSchemeUsedDao.selectPatientPeriodList(paramMap);
		if(!CollectionUtils.isEmpty(periodList)){
			for(int i = 0 ;i<periodList.size() ;i++){
				Map<String,Object> tempPeriod =  periodList.get(i);
				String key = (String)tempPeriod.get("periodId");

				List<Map<String,Object>> foodList = new ArrayList<Map<String,Object>>();
				if(!CollectionUtils.isEmpty(periodFoodList)){
					for(int j = 0 ;j<periodFoodList.size() ;j++){
						Map<String,Object> temp =  periodFoodList.get(j);
						String keyId = (String)temp.get("periodId");
						if(null!=keyId && keyId.equals(key)){
							foodList.add(periodFoodList.get(j));
						}
					}
				}
				periodList.get(i).put("foods", foodList);
			}
		}
		rspMap.put("periodHeads", periodList);

		List<Map<String,Object>> situationList = iNutritionSchemeUsedDao.selectPatientSituationList(paramMap);
		if(!CollectionUtils.isEmpty(situationList)){
			Map<String,List<Map<String,Object>>> dataFoods= new LinkedHashMap<String,List<Map<String,Object>>>();
			Map<String,Object> dataFood= null;
			for(int i = 0;i<situationList.size() ;i++){
				//已天为单位
				dataFood = new HashMap<String,Object>();
				dataFood.put("foodContent",situationList.get(i).get("foodContent"));
				dataFood.put("dealState",situationList.get(i).get("dealState"));
				dataFood.put("userAmount",situationList.get(i).get("userAmount"));
				dataFood.put("periodId",situationList.get(i).get("periodId"));
				dataFood.put("foodId",situationList.get(i).get("foodId"));
				dataFood.put("doctorAmount",situationList.get(i).get("doctorAmount"));
				dataFood.put("defaultAmount",situationList.get(i).get("defaultAmount"));
				dataFood.put("actualAmount",situationList.get(i).get("actualAmount"));
				dataFood.put("time",situationList.get(i).get("time"));
				dataFood.put("situationId",situationList.get(i).get("situationId"));

				String keyday = situationList.get(i).get("day") +"";
				if(dataFoods.containsKey(keyday)){
					dataFoods.get(keyday).add(dataFood);
				}else{
					List<Map<String,Object>> temp = new ArrayList<Map<String,Object>>();
					temp.add(dataFood);
					dataFoods.put(keyday,temp);
				}
			}

			//查询营养元素标准
			paramMap.clear();
			paramMap.put("pcourseId",ptNtschemeCourse.getId());
//			paramMap.put("status",Constants.COMMON_STATUS_NOMAL);

			//疗程营养元素标准
			List<Map<String,Object>> courseNutritionList = iNutritionSchemeUsedDao.selectPatientCourseNutrients(paramMap);
			//食物含有的营养元素标准
//			paramMap.put("courseVersionId",ptNtschemeCourse.getCourseversionId());
			List<Map<String,Object>> foodNutrientlist = iNutritionSchemeUsedDao.selectPatientFoodNutrients(paramMap);
			Map<String,List<Map<String,Object>>> foodNutrientMap= new LinkedHashMap<String,List<Map<String,Object>>>();
			//封装成 foodId = 食物元素含量 map结构
			if(!CollectionUtils.isEmpty(foodNutrientlist)){
				for(int i = 0 ;i< foodNutrientlist.size();i++){
					String foodKey = foodNutrientlist.get(i).get("foodId") +"";
					if(foodNutrientMap.containsKey(foodKey)){
						foodNutrientMap.get(foodKey).add(foodNutrientlist.get(i));
					}else{
						List<Map<String,Object>> temp = new ArrayList<Map<String,Object>>();
						temp.add(foodNutrientlist.get(i));
						foodNutrientMap.put(foodKey,temp);
					}
				}
			}
			rspMap.put("courseNutritions",courseNutritionList);

			//封装成 以day为一行数据格式   day里面有各个餐次 情况
			for (Map.Entry<String,List<Map<String,Object>>> entry : dataFoods.entrySet()) {
				String key = entry.getKey();
				Map<String,Object> situationMap = new HashMap<String,Object>();
				situationMap.put("day",key);
				situationMap.put("foodList",entry.getValue());

				if(!CollectionUtils.isEmpty(entry.getValue())){
					situationMap.put("time",entry.getValue().get(0).get("time"));//日期
					situationMap.put("remark",entry.getValue().get(0).get("remark"));//备注
				}

				List<Map<String,Object>> dayNutrientlist  = null;//每天营养元素含量

				//每一天营养元素 含量标准和实际食用量
				if(!CollectionUtils.isEmpty(courseNutritionList)){
					dayNutrientlist = new ArrayList<Map<String,Object>>();

					for(int i =0;i<courseNutritionList.size();i++){
						Map<String,Object> tempMap = new HashMap<String,Object>();
						tempMap.putAll(courseNutritionList.get(i));

						String nutrientsId = (String)courseNutritionList.get(i).get("nutrientsId");
						float actualAmount = 0;
						//每天 每种食物营养元素含量(一种食物多种营养元素)
						for(int k = 0;k<entry.getValue().size();k++){
							String foodId = entry.getValue().get(k).get("foodId")+"";
							String foodTotalStr = entry.getValue().get(k).get("actualAmount")+"";
							List<Map<String,Object>> foodNutrients = foodNutrientMap.get(foodId);
							if(!CollectionUtils.isEmpty(foodNutrients)){
								//每种食物 元素含量
								float foodTotal = 0;
								if(ToolUtils.isNumeric(foodTotalStr)){
									foodTotal = Float.parseFloat(foodTotalStr);
								}
								for(int j =0;j<foodNutrients.size();j++){
									if(nutrientsId.equals(foodNutrients.get(j).get("nutrientsId"))){
										Object nutrientsValueStr = foodNutrients.get(j).get("nutrientsValue");
										Object nutrientsPerStr = foodNutrients.get(j).get("nutrientsPer");
										/*String foodTotalStr = (String)foodNutrients.get(j).get("total");这个默认食物重量 */
										float nutrientsValue = 0;
										float nutrientsPer = 0;


										//本次添加食物 包含元素含量   == 食物重量/最小单位量*单位元素含量
										float addValue = 0;

										if(null !=nutrientsValueStr && ToolUtils.isNumeric(nutrientsValueStr.toString())){
											nutrientsValue = Float.parseFloat(nutrientsValueStr.toString());
										}
										if(null !=nutrientsPerStr && ToolUtils.isNumeric(nutrientsPerStr.toString())){
											nutrientsPer = Float.parseFloat(nutrientsPerStr.toString());
										}
										if(nutrientsPer ==  0){
											nutrientsPer = 100; //默认为每100g 含量
										}
										addValue = (foodTotal/nutrientsPer)*nutrientsValue;

										if(addValue > 0){//小于0 不修改
											actualAmount+=addValue;
										}
										break;
									}
								}
							}
						}
						BigDecimal amount=new BigDecimal(actualAmount);
						double f = amount.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
						tempMap.put("actualAmount",f);
						dayNutrientlist.add(tempMap);
					}
				}
				situationMap.put("nutrientList", dayNutrientlist);
				dataSituations.add(situationMap);
			}
		}
		rspMap.put("situations",dataSituations);
		rspMap.put("stopTime",ptNtschemeCourse.getStopTime());
		rspMap.put("ptCourseId",ptNtschemeCourse.getId());
		rspMap.put("ptCourseName",ptNtschemeCourse.getCourseName());
		rspMap.put("ptCourseNo",ptNtschemeCourse.getPcourseNo());
		rspMap.put("remark",ptNtschemeCourse.getRemark());
		rspMap.put("status",ptNtschemeCourse.getStatus());

		return rspMap;
	}

	@Override
	@Transactional
	public Map<String, Object> patientCourseStartDaySet(Map<String, Object> map)
			throws Exception {
		logger.info("in patientCourseStartDaySet");
//		String ptSchemeId = (String)map.get("ptSchemeId");
		String authorId = (String)map.get("authorId");
		String ptCourseId = (String)map.get("ptCourseId");
		String startDateStr = (String)map.get("startDate");
		String ptSchemeId = (String)map.get("ptSchemeId");

		String stopTime = DateUtil.getSysDateA();
		//  更新前 检查方案或阶段下 其他疗程是否状态   将该疗程之前的疗程置为终止状态
		Map<String,Object> paramMap = new HashMap<String,Object>();
		//查询用户是否存在
		paramMap.put("ptCourseId",ptCourseId);
		paramMap.put("excludeStatus",Constants.COMMON_STATUS_DELETE);
		paramMap.put("ptSchemeId",ptSchemeId);
		PtNtschemeCourse ptNtschemeCourse = iNutritionSchemeUsedDao.selectPatientCourseInfo(paramMap);
		if(null == ptNtschemeCourse){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_NUTRITION_COURSEVERSION_NOT_EXISTS_ERROR,"患者疗程信息不存在");
		}

		int courseNo = ptNtschemeCourse.getPcourseNo();
		paramMap.clear();
		paramMap.put("ptSchemeId",ptSchemeId);
		paramMap.put("ptStageId",ptNtschemeCourse.getPstageId());
		paramMap.put("status",Constants.COMMON_STATUS_STOP);
		paramMap.put("ptCourseNo",courseNo);
		paramMap.put("stopTime",stopTime);
		paramMap.put("updateAuthor",authorId);
		iNutritionSchemeUsedDao.updatePtSchemeCourse(paramMap);

		paramMap.clear();
		paramMap.put("ptCourseId",ptCourseId);
		paramMap.put("startDate",startDateStr);
		paramMap.put("createTime",DateUtil.getSysDateA());
		paramMap.put("createAuthor",authorId);
		paramMap.put("status",Constants.COMMON_STATUS_ENABLE);
		iNutritionSchemeUsedDao.updateCourseStartDate(paramMap);

		List<Map<String,Object>> updateList = new ArrayList<Map<String,Object>>();
		Map<String,Object> updateMap = null;

		// 查询所有饮食情况
		paramMap.clear();
		paramMap.put("ptCourseId",ptCourseId);
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		Date startDate = DateUtil.getDate_8(startDateStr);
		List<PtCourseSituation> courseSituation = iNutritionSchemeUsedDao.selectPatientSituations(paramMap);
		if(!CollectionUtils.isEmpty(courseSituation)){
			for(int i = 0 ;i<courseSituation.size();i++){
				updateMap= new HashMap<String,Object>();
				updateMap.put("id",courseSituation.get(i).getId());
				int day = courseSituation.get(i).getDay();
				if(day >= 1){
					day = day-1;
				}
				String time =DateUtil.getDate_8(DateUtil.addDay(startDate, day));
				updateMap.put("time",time);
				updateMap.put("day",day);
				updateList.add(updateMap);
			}
		}
		if(!CollectionUtils.isEmpty(updateList)){
			iNutritionSchemeUsedDao.updateSituationTimes(updateList);
		}

		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public Map<String, Object> patientSituationModify(Map<String, Object> map) throws Exception {
		logger.info("in patientSituationModify");
        String tenantId = (String)map.get("tenantId");
        String authorId = (String)map.get("authorId");
        String type = (String)map.get("type");
        String amount = (String)map.get("amount");
        String authorName = (String)map.get("authorName");

        String currenTime = DateUtil.getSysDateA();
        List<String> situationList = (List<String>)map.get("situationList");

		Map<String,Object> updateMap = new HashMap<String,Object>();
		updateMap.put("situations", situationList);
		if(Constants.NUTRIENTS_SITUATION_DOCTOR_DEFAULT.equals(type)){
			updateMap.put("defaultAmount",Float.parseFloat(amount));
		}else{
			updateMap.put("doctorAmount",Float.parseFloat(amount));
			updateMap.put("actualAmount",Float.parseFloat(amount));
			updateMap.put("dealState", Constants.NUTRIENTS_SITUATION_DOCTOR_SIGN);
		}
		updateMap.put("updateTime",currenTime);
		updateMap.put("updateAuthor",authorId);
		iNutritionSchemeUsedDao.updateSituationAmount(updateMap);

		//保存修改记录--
		List<PtNtsituationModifyLog> insertList = new ArrayList<PtNtsituationModifyLog>();
		PtNtsituationModifyLog situationModifyLog = null;
		for(int i = 0 ;i<situationList.size();i++){
			situationModifyLog =  new PtNtsituationModifyLog();
			situationModifyLog.setId(SeqUtil.getSeqNo());
			situationModifyLog.setCreateTime(currenTime);
			if(Constants.NUTRIENTS_SITUATION_DOCTOR_DEFAULT.equals(type)){
				situationModifyLog.setDefaultAmount(Float.parseFloat(amount));
				situationModifyLog.setRemark("生成计划");
			}else{
				situationModifyLog.setActualAmount(Float.parseFloat(amount));
				situationModifyLog.setRemark("修改数据");
			}
			situationModifyLog.setType(type);
			situationModifyLog.setModifyId(authorId);
			situationModifyLog.setSituationId(situationList.get(i));
			situationModifyLog.setTenantId(tenantId);
			situationModifyLog.setModifyName(authorName);
			insertList.add(situationModifyLog);
		}
		if(!CollectionUtils.isEmpty(insertList)){
			iNutritionSchemeUsedDao.savePtNtsituationLog(insertList);
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> patientSituationModifyHis(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSituationModifyHis");
		String situationId = (String)map.get("situationId");
		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("situationId",situationId);

		List<Map<String,Object>> list = iNutritionSchemeUsedDao.selectSituationLogs(paramMap);
		if(!CollectionUtils.isEmpty(list)){
			for(int i =0;i<list.size();i++){
				map = list.get(i);
				list.get(i).put("createTime",DateUtil.getTimeStampSec(map.get("createTime").toString()));
			}
		}
		return list;
	}

	@Override
	@Transactional
	public Map<String,Object> patientSchemeStop(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeStop");
		//将患者当前应用方案 状态置为停止
		String stopTime = DateUtil.getSysDateA(); //停止时间
		String userId = (String)map.get("userId");
		String ptSchemeId = (String)map.get("ptSchemeId");
//		String tenantId = (String)map.get("tenantId");
		String updateAuthor = (String)map.get("authorId");
		String remark = (String)map.get("remark");

		//查询患者|患者方案是否存在
		Map<String,Object> paramMap = new HashMap<String,Object>();
		/*paramMap.put("userId", userId);
		paramMap.put("tenantId", tenantId);
		Patient patient = patientDao.selectById(map);
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,
        			"患者信息不存在");
		}*/

		//查询应用方案
		paramMap.put("ptSchemeId",ptSchemeId);
//		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		List<PtNtschemeInfo> ptNtschemes = iNutritionSchemeUsedDao.selectPatientSchemeInfo(paramMap);
		//查询应用方案信息

		if(CollectionUtils.isEmpty(ptNtschemes)){
			throw new AppException(ErrorCode.NUTRITION_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,"患者方案信息不存在");
		}

		//更新应用方案状态
		Map<String,Object> updateMap = new HashMap<String,Object>();
		updateMap.put("stopTime", stopTime);
		updateMap.put("ptSchemeId",ptSchemeId);
		updateMap.put("userId",userId);
		updateMap.put("status",Constants.COMMON_STATUS_STOP);
		updateMap.put("remark",remark);
		updateMap.put("updateAuthor", updateAuthor);
		//更新正常状态疗程为 停止
//		updateMap.put("oldStatus",Constants.COMMON_STATUS_NOMAL);
		iNutritionSchemeUsedDao.updatePtSchemeInfo(updateMap);

		updateMap.put("remark",remark+"-停止阶段");
		iNutritionSchemeUsedDao.updatePtSchemeStage(updateMap);

		//更新疗程状态为停止
		updateMap.put("remark",remark+"-停止疗程");
		iNutritionSchemeUsedDao.updatePtSchemeCourse(updateMap);

		return null;
	}

	@Override
	@Transactional
	public Map<String, Object> patientSchemeChange(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeStop");
		//先停应用方案
//		patientSchemeStop(map);
		//再启用方案
		Map<String, Object> rspMap = patientSchemeUsedCache(map);
		return rspMap;
	}

	@Override
	public List<Map<String, Object>> patientSchemeList(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeList");
		List<Map<String, Object>>  list = new ArrayList<Map<String, Object>>();

//		Map<String,Object> paramMap = new HashMap<String,Object>();
//		paramMap.putAll(map);
		List<String> queueIdArray = new ArrayList<String>();
		// 根据当前登录账号获取，其可以查看的队列id
        queueIdArray = fllowQueueService.getQueueArrByAuthority(map);
        if(CollectionUtils.isEmpty(queueIdArray)){
			logger.warn("该账号无可查看到的患者信息...arg==" + map.toString());
			return list;
		}

        map.put("queueIdIn",queueIdArray);
        map.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
        int page =  (map.get("page")!=null && !StringUtils.isEmpty(map.get("page").toString())) ? Integer.parseInt(map.get("page").toString()) : 1;
		int rows =  (map.get("rows")!=null && !StringUtils.isEmpty(map.get("rows").toString())) ? Integer.parseInt(map.get("rows").toString()) : 12;

		map.put("start", rows*(page-1));
		map.put("end", rows);

		Object searchObj = map.get("searchCondition");
		Object searchCondition = (searchObj!=null &&!StringUtils.isEmpty(searchObj)) ? "%"+searchObj.toString()+"%" : searchObj ;
		map.put("searchCondition",searchCondition);
		map.put("excludeStatus",Constants.COMMON_STATUS_DELETE);//排除已删除方案

		map.put("enableStatus",Constants.COMMON_STATUS_ENABLE);//当前启用疗程
		list = iNutritionSchemeUsedDao.selectPatientSchemeList(map);
		Map<String, Object> mapTemp =null;
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				mapTemp = list.get(i);
				if(null == mapTemp){
					list.clear();//可能查出一条空数据
					break;
				}
				if(null == mapTemp.get("currentStageNum")){
					list.get(i).put("currentStageNum","1");//如果没有启用状态则取第一个阶段
				}
				//监测时间
				list.get(i).put("createTime",DateUtil.getTimeStampSec(mapTemp.get("createTime").toString()));
				//录入时间
				mapTemp = null;
			}
		}

		return list;
	}

	@Override
	public int patientSchemeCount(Map<String, Object> map) throws Exception {
		int i  = iNutritionSchemeUsedDao.selectPatientSchemeCount(map);
		return i;
	}

	@Override
	public int CountSchemeListQry(Map<String, Object> paramMap) throws Exception {
		return iNutritionSchemeUsedDao.selectSchemeCount(paramMap);
	}


	@Override
	public List<Map<String, Object>> schemeListQry(Map<String, Object> paramMap)
			throws Exception {
		logger.info("in schemeVersionListQry");
		/*int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 100;*/

		Object schemeTypeNameObject = paramMap.get("schemeTypeName");
		Object schemeTypeName = schemeTypeNameObject!=null ? "%"+schemeTypeNameObject.toString()+"%" : schemeTypeNameObject ;

		Object schemeNameObj = paramMap.get("schemeName");
		Object schemeName = schemeNameObj!=null ? "%"+schemeNameObj.toString()+"%" : schemeNameObj ;

		paramMap.put("schemeTypeName",schemeTypeName);
		paramMap.put("schemeName",schemeName);

		/*paramMap.put("start", page);
		paramMap.put("end", rows);*/
		paramMap.put("tenantSchemeType",Constants.COMMON_TYPE_TENANT);
		paramMap.put("privateSchemeType",Constants.COMMON_TYPE_PRIVATE);
		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		List<Map<String, Object>> list= iNutritionSchemeUsedDao.selectSchemeList(paramMap);
		if(!CollectionUtils.isEmpty(list)){
			for(int i = 0;i<list.size();i++){
				Map<String, Object> temp = list.get(i);
				list.get(i).put("createTime",DateUtil.getTimeStampSec(temp.get("createTime").toString()));
			}
		}
		return list;
	}

	@Override
	@Transactional
	public Map<String, Object> patientSchemeUsedCache(Map<String, Object> map)
			throws Exception {
		logger.info("in patientSchemeUsedCache");
		Map<String,Object> rspMap = new HashMap<String,Object>();

		String createAuthor = (String)map.get("authorId");
		String schemeVersionId = (String)map.get("schemeVersionId");
		String userId = (String)map.get("userId");
		String tenantId = (String)map.get("tenantId");
		String currenTime = DateUtil.getSysDateA();

		Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("userId", userId);
		paramMap.put("tenantId", tenantId);
		Patient patient = patientDao.selectById(map);
		if(null == patient){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
		}

		// 患者当前已经有启用的营养方案  停止
		if(!StringUtils.isEmpty(map.get("ptSchemeId"))){
			this.patientSchemeStop(map);
		}else{
			paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
			List<PtNtschemeInfo> schmeInfos = iNutritionSchemeUsedDao.selectPatientSchemeInfoUsed(paramMap);
			if(!CollectionUtils.isEmpty(schmeInfos)){
				PtNtschemeInfo schmeInfo = schmeInfos.get(0);
				paramMap.clear();
				paramMap.put("ptSchemeId",schmeInfo.getId());
				paramMap.putAll(map);
				this.patientSchemeStop(paramMap);
			}
		}


		//保存到redis
		String schemeVersionKey =  Constants.NUTRITION_SCHEME_VERSION_KEY +schemeVersionId;

		Jedis jedis = null;
		String schemeStr ="";
        try {
            jedis = jedisPool.getResource();
            jedis.select(Constants.REDIS_DB_INDEX_NUTRITIOUS);
            schemeStr = jedis.get(schemeVersionKey);
        }catch (Exception jex) {
            logger.error("redis连接异常..." + jex.getMessage());
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR, "Redis缓存连接失败!"));
        } finally {
            if (null != jedis) {
                try {
                    jedis.close();
                    logger.warn("close redis connection...");
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,
                            "Redis缓存关闭失败!"));
                }
            }
        }

        NtSchemeVersion version = null;
        if(!StringUtils.isEmpty(schemeStr)){
        	try{
        		version= JSON.parseObject(schemeStr, NtSchemeVersion.class);
        	}catch(Exception e){
            	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,"方案信息数据格式不存在");
        	}
        }else{
//        	this.patientSchemeUsed(map);
        	throw new AppException(ErrorCode.NUTRITION_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR,"方案信息不存在或该方案还未发布（进入方案详情点击发布按钮）");
        }

		List<PtNtschemeStage> ptStageList = new ArrayList<PtNtschemeStage>();
		List<PtNtschemeCourse> ptCourselist = new ArrayList<PtNtschemeCourse>();
		List<PtNtcourseFood> ptCourseFoodlist = new ArrayList<PtNtcourseFood>();
		List<PtCourseSituation> ptCourseSituationlist = new ArrayList<PtCourseSituation>();
		List<PtNtcoursePeriodtime> ptCoursePeriodlist = new ArrayList<PtNtcoursePeriodtime>();
		List<PtNtcourseNutrients> ptCourseNutrientlist = new ArrayList<PtNtcourseNutrients>();

		//构建方案版本信息
		PtNtschemeInfo ptScheme= new PtNtschemeInfo();
		ptScheme.setId(SeqUtil.getSeqNo());
		ptScheme.setCreateAuthor(createAuthor);
		ptScheme.setCreateTime(currenTime);
		ptScheme.setStatus(Constants.COMMON_STATUS_NOMAL); //正常
		ptScheme.setTenantId(tenantId);
		ptScheme.setPschmeName(version.getVersionName());
		ptScheme.setUserId(userId);
		ptScheme.setSchemeDesc(version.getVersionDesc());
		ptScheme.setSchemeversionId(schemeVersionId);
		iNutritionSchemeUsedDao.savePatientScheme(ptScheme);
		rspMap.put("ptNtschemeId",ptScheme.getId());

		//根据id查询方案阶段
		List<NtSchemeStage> stageList = version.getStageList();

		PtNtschemeStage ptSchemeStage = null;
		if(!CollectionUtils.isEmpty(stageList)){
			for(int i =0;i<stageList.size();i++){
				ptSchemeStage = new PtNtschemeStage();
				ptSchemeStage.setId(SeqUtil.getSeqNo());
				ptSchemeStage.setCreateAuthor(createAuthor);
				ptSchemeStage.setCreateTime(currenTime);
				ptSchemeStage.setId(SeqUtil.getSeqNo());
				ptSchemeStage.setPschemeId(ptScheme.getId());
				ptSchemeStage.setStageName(stageList.get(i).getStageName());
				ptSchemeStage.setStageNo(stageList.get(i).getStageNo());
				if(1 == stageList.get(i).getStageNo()){//第一个阶段默认为启用
					ptSchemeStage.setStatus(Constants.COMMON_STATUS_ENABLE);
				}else{
					ptSchemeStage.setStatus(Constants.COMMON_STATUS_NOMAL);
				}

				ptStageList.add(ptSchemeStage);

				List<NtSchemeCourseVersion> coures = stageList.get(i).getCourseVersionList();
				if(!CollectionUtils.isEmpty(coures)){
					PtNtschemeCourse ptCourse = null;
					for(int j = 0 ; j <coures.size();j++){
						String courseVersionId = coures.get(j).getId();
						int pcourseNo  =coures.get(j).getCourseNo();

						ptCourse = new PtNtschemeCourse();
						ptCourse.setId(SeqUtil.getSeqNo());
						ptCourse.setCourseName(coures.get(j).getCourseName());
						ptCourse.setCourseversionId(courseVersionId);
						ptCourse.setCreateAuthor(createAuthor);
						ptCourse.setCreateTime(currenTime);
						ptCourse.setPschemeId(ptScheme.getId());
						ptCourse.setPstageId(ptSchemeStage.getId());
						ptCourse.setUserId(userId);
						ptCourse.setTenantId(tenantId);
						ptCourse.setCourseTotal(coures.get(j).getCourseTotal());
						ptCourse.setPcourseNo(pcourseNo);
						ptCourse.setStatus(Constants.COMMON_STATUS_NOMAL);
						ptCourselist.add(ptCourse);

						//疗程标准
						List<NtCourseNutrients> courseNutrientList = coures.get(j).getCourseNutrientList();
						if(!CollectionUtils.isEmpty(courseNutrientList)){
							PtNtcourseNutrients courseNutrient = null;
							for(int k = 0;k<courseNutrientList.size();k++){
								courseNutrient = new PtNtcourseNutrients();
								courseNutrient.setId(SeqUtil.getSeqNo());
								courseNutrient.setActualAmount(courseNutrientList.get(k).getActualAmount());
								courseNutrient.setAverageAmount(courseNutrientList.get(k).getAverageAmount());
								courseNutrient.setCreateAuthor(createAuthor);
								courseNutrient.setCreateTime(currenTime);
								courseNutrient.setMaxAmount(courseNutrientList.get(k).getMaxAmount());
								courseNutrient.setMinAmount(courseNutrientList.get(k).getMinAmount());
								courseNutrient.setPcourseId(ptCourse.getId());
								courseNutrient.setNutrientCode(courseNutrientList.get(k).getNutrientsCode());
								courseNutrient.setNutrientsId(courseNutrientList.get(k).getNutrientsId());
								courseNutrient.setRemark(courseNutrientList.get(k).getRemark());
								ptCourseNutrientlist.add(courseNutrient);
							}
						}

						PtNtcoursePeriodtime periodTime = null;
						List<NtCoursePeriodtime> periodList = coures.get(j).getCoursePeriodList();
						//应用时间段ID和疗程库时间段对应关系
						Map<String,String> periodMap = new HashMap<String,String>();
						if(!CollectionUtils.isEmpty(periodList)){
							for(int k =0;k<periodList.size();k++){
								periodTime = new PtNtcoursePeriodtime();
								periodTime.setId(SeqUtil.getSeqNo());
								periodTime.setCreateAuthor(createAuthor);
								periodTime.setCreateTime(currenTime);
								periodTime.setEndTime((String)periodList.get(k).getEndTime());
								periodTime.setStartTime((String)periodList.get(k).getStartTime());
								periodTime.setPcourseId(ptCourse.getId());
								periodTime.setPeriodName((String)periodList.get(k).getPeriodName());
								periodTime.setTenantId(tenantId);
								ptCoursePeriodlist.add(periodTime);

								String periodId = (String)periodList.get(k).getId();
								periodMap.put(periodId, periodTime.getId());
							}
							//饮食情况列表
							PtNtcourseFood ptNtcourseFood = null;
							List<NtCourseFood> courseFoodList = coures.get(j).getCourseFoodList();

							PtCourseSituation ptCourseSituation=null;
							if(!CollectionUtils.isEmpty(courseFoodList)){
								for(int l=0;l<courseFoodList.size();l++){
									ptNtcourseFood = new PtNtcourseFood();
									ptNtcourseFood.setId(SeqUtil.getSeqNo());
									ptNtcourseFood.setCreateAuthor(createAuthor);
									ptNtcourseFood.setCreateTime(currenTime);
									ptNtcourseFood.setFoodId(courseFoodList.get(l).getFoodId());
									ptNtcourseFood.setPcourseId(ptCourse.getId());
									ptNtcourseFood.setStatus(Constants.COMMON_STATUS_NOMAL);
									ptNtcourseFood.setTotal(courseFoodList.get(l).getTotal());
									ptNtcourseFood.setPeriodId(periodMap.get(courseFoodList.get(l).getPeriodId()));
									ptCourseFoodlist.add(ptNtcourseFood);

									for(int m = 0 ;m<ptCourse.getCourseTotal();m++){
										ptCourseSituation = new PtCourseSituation();
										ptCourseSituation.setId(SeqUtil.getSeqNo());
										ptCourseSituation.setDay(m+1);
										ptCourseSituation.setCreateTime(currenTime);
										if(null != courseFoodList.get(l).getTotal()){
											ptCourseSituation.setDefaultAmount(courseFoodList.get(l).getTotal());
										}
										ptCourseSituation.setFoodId(courseFoodList.get(l).getFoodId());
										ptCourseSituation.setPcourseId(ptCourse.getId());
										ptCourseSituation.setPeriodId(periodMap.get(courseFoodList.get(l).getPeriodId()));
										ptCourseSituation.setPschemeId(ptScheme.getId());
										ptCourseSituation.setStatus(Constants.COMMON_STATUS_NOMAL);
										ptCourseSituation.setUserId(userId);
										ptCourseSituation.setTenantId(tenantId);
										ptCourseSituationlist.add(ptCourseSituation);
									}
								}
							}
						}
					}
				}
			}

		}else{
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_NUTRITION_STAGE_NOT_EXISTS,"方案没有配置阶段");
		}

		if(!CollectionUtils.isEmpty(ptStageList)){
			iNutritionSchemeUsedDao.savePatientStages(ptStageList);
		}
		if(!CollectionUtils.isEmpty(ptCourselist)){
			iNutritionSchemeUsedDao.savePatientCourse(ptCourselist);
		}
		if(!CollectionUtils.isEmpty(ptCoursePeriodlist)){
			iNutritionSchemeUsedDao.savePatientPeriod(ptCoursePeriodlist);
		}
		if(!CollectionUtils.isEmpty(ptCourseFoodlist)){
			iNutritionSchemeUsedDao.savePatientCourseFood(ptCourseFoodlist);
		}
		if(!CollectionUtils.isEmpty(ptCourseSituationlist)){
			iNutritionSchemeUsedDao.savePatientSituation(ptCourseSituationlist);
		}
		if(!CollectionUtils.isEmpty(ptCourseNutrientlist)){
			iNutritionSchemeUsedDao.savePatientCourseNutrients(ptCourseNutrientlist);
		}

		return rspMap;
	}

	@Override
	@Transactional
	public Map<String, Object> patientStageUsed(Map<String, Object> map)
			throws Exception {
		//将患者当前应用方案 状态置为停止
		String stopTime = DateUtil.getSysDateA(); //停止时间
		String ptSchemeId = (String)map.get("ptSchemeId");
		String ptStageId = (String)map.get("ptStageId");
		String updateAuthor = (String)map.get("authorId");
		String remark = (String)map.get("remark");

		Map<String,Object> paramMap = new HashMap<String,Object>();
		//查询应用方案
		paramMap.put("ptSchemeId",ptSchemeId);
		paramMap.put("ptStageId",ptStageId);
//		paramMap.put("status",Constants.COMMON_STATUS_NOMAL);
		List<PtNtschemeStage> stageList = iNutritionSchemeUsedDao.selectPatientStageList(paramMap);
		//查询患者应用方案阶段是否存在
		if(CollectionUtils.isEmpty(stageList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_NUTRITION_STAGE_NOT_EXISTS,"患者营养方案不存");
		}

		PtNtschemeStage stage = stageList.get(0);
		//更新应用方案状态
		Map<String,Object> updateMap = new HashMap<String,Object>();
		//ptStageId
		updateMap.put("status",Constants.COMMON_STATUS_ENABLE);
		updateMap.put("ptStageId",stage.getId());
		updateMap.put("ptSchemeId",ptSchemeId);
		updateMap.put("updateAuthor", updateAuthor);
		updateMap.put("remark","启用阶段");
		iNutritionSchemeUsedDao.updatePtSchemeStage(updateMap);

		updateMap.clear();
		updateMap.put("ptSchemeId",ptSchemeId);
		updateMap.put("stopTime", stopTime);
		updateMap.put("remark",remark+":停止阶段");
		updateMap.put("status",Constants.COMMON_STATUS_STOP);
		updateMap.put("ptStageNo",stage.getStageNo());
		iNutritionSchemeUsedDao.updatePtSchemeStage(updateMap);

		//更新疗程状态为停止
		paramMap.clear();
		paramMap.put("ptSchemeId",ptSchemeId);
		paramMap.put("status",Constants.COMMON_STATUS_STOP);
		paramMap.put("updateAuthor",updateAuthor);
		paramMap.put("remark",remark+":停止阶段-关联停疗程");
		paramMap.put("stopTime",stopTime);
		paramMap.put("ptStageNo",stage.getStageNo());
		iNutritionSchemeUsedDao.updatePtSchemeCourseByStageNo(paramMap);

		// 查询所有饮食情况
//		paramMap.clear();
//		paramMap.put("ptSchemeId",ptSchemeId);
//		paramMap.put("status",Constants.COMMON_STATUS_STOP);
//		paramMap.put("updateAuthor",updateAuthor);
//		paramMap.put("updateTime", stopTime);
//		iNutritionSchemeUsedDao.updateSituation(paramMap);

		return null;
	}

	@Override
	@Transactional
	public Map<String, Object> patientCourseStop(Map<String, Object> map)
			throws Exception {
		logger.info("in patientCourseStop");
//		String ptSchemeId = (String)map.get("ptSchemeId");
		String authorId = (String)map.get("authorId");
		String ptCourseId = (String)map.get("ptCourseId");

		String stopTime = DateUtil.getSysDateA();
		Map<String,Object> paramMap = new HashMap<String,Object>();
		//查询用户是否存在
		paramMap.put("ptCourseId",ptCourseId);
		PtNtschemeCourse ptNtschemeCourse = iNutritionSchemeUsedDao.selectPatientCourseInfo(paramMap);
		if(null == ptNtschemeCourse){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_NUTRITION_COURSEVERSION_NOT_EXISTS_ERROR,"患者疗程信息不存在");
		}else{
			if(Constants.COMMON_STATUS_STOP.equals(ptNtschemeCourse.getStatus())){
				return null;
			}
		}

		paramMap.clear();
		paramMap.put("ptSchemeId",ptNtschemeCourse.getPschemeId());
		paramMap.put("status",Constants.COMMON_STATUS_STOP);
		paramMap.put("ptCourseId",ptCourseId);
		paramMap.put("updateAuthor",authorId);
		paramMap.put("stopTime",stopTime);
		iNutritionSchemeUsedDao.updatePtSchemeCourse(paramMap);

		// 查询所有饮食情况
		paramMap.clear();
		paramMap.put("ptCourseId",ptCourseId);
		paramMap.put("ptSchemeId",ptNtschemeCourse.getPschemeId());
		paramMap.put("status",Constants.COMMON_STATUS_STOP);
		paramMap.put("updateAuthor",authorId);
		paramMap.put("updateTime", stopTime);
		iNutritionSchemeUsedDao.updateSituation(paramMap);
		return null;
	}

	@Override
	public Map<String, Object> getStatisticsData(Map<String, Object> map)
			throws Exception {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		Map<String,Object> rspMap = new HashMap<String,Object>();
		List<String> schemeStatus = new ArrayList<String>();
		// 根据当前登录账号获取，其可以查看的队列id
		List<String> queueIdArray = fllowQueueService.getQueueArrByAuthority(map);
		//方案推送总数
		paramMap.put("queueIdIn",queueIdArray);
        paramMap.put("userStatus",Constants.QUEUE_STATUS_NOMAL);
        paramMap.put("tenantId", map.get("tenantId"));
        int allPatient =0,nowPatient=0,managerPatient=0,schemeCount=0;
        if(CollectionUtils.isEmpty(queueIdArray)){
        	rspMap.put("allNumber", allPatient);
            rspMap.put("todayNumber", nowPatient);
            rspMap.put("managerMumber", managerPatient);
            rspMap.put("pushNumber", schemeCount);
    		return rspMap;
		}
		//全部患者总数
        allPatient = iNutritionSchemeUsedDao.selectSchemeUsedPatientCount(paramMap);

		//管理中患者总数
        schemeStatus.add(Constants.COMMON_STATUS_NOMAL);
        schemeStatus.add(Constants.COMMON_STATUS_SUSPEND);
        schemeStatus.add(Constants.COMMON_STATUS_NOMAL);
        paramMap.put("schemeStatus",schemeStatus);
        managerPatient = iNutritionSchemeUsedDao.selectSchemeUsedPatientCount(paramMap);

        //今日新增应用患者 数
        String nowTime = DateUtil.getCurrDate();
        paramMap.put("nowTime",nowTime);
        nowPatient = iNutritionSchemeUsedDao.selectSchemeUsedPatientCount(paramMap);

        schemeCount =iNutritionSchemeUsedDao.selectPatientSchemeCount(paramMap);

        rspMap.put("allNumber", allPatient);
        rspMap.put("todayNumber", nowPatient);
        rspMap.put("managerMumber", managerPatient);
        rspMap.put("pushNumber", schemeCount);
		return rspMap;
	}

	@Override
	public Map<String, Object> patientScheduleUpload(Map<String, Object> map)throws Exception {
		Map<String,Object> rspMap = new HashMap<String,Object>();
        String userId = (String)map.get("userId");
        String time = (String)map.get("time");
        String foodId = (String)map.get("foodId");
        String total = (String)map.get("total");
        String periodId = (String)map.get("periodId");//时间段id
        String isCancel = (String)map.get("isCancel");//是否取消上传，等于0则为取消
    	String tenantId = weightDao.getUserTenantIdByUserId(userId);
    	if(StringUtils.isEmpty(tenantId)){
    		throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"患者信息不存在");
    	}
        //时间
      	String currenTime = DateUtil.getSysDateA();
      	//新增加的食物
      	List<PtCourseSituation> ptCourseSituationlist = new ArrayList<PtCourseSituation>();
    	String situationId = (String)map.get("situationId");
    	if(!StringUtils.isEmpty(situationId)){//食物在计划列表中
    		rspMap.put("situationId", situationId);
    		//先查下
    		Map<String,Object> updateMap = new HashMap<String,Object>();
    		updateMap.put("situationId", situationId);
    		PtCourseSituation situation = iNutritionSchemeUsedDao.selectPatientSituationById(updateMap);
    		if(null == situation){
    			return null;
    		}
    		List<String> situationList = new ArrayList<String>();
    		situationList.add(situationId);
    		updateMap.clear();
    		//double amount = situation.getDefaultAmount(); //客户端上传 代表完成使用
    		updateMap.put("situations", situationList);
    		updateMap.put("userAmount",total);
    		updateMap.put("actualAmount",total);
    		updateMap.put("dealState", Constants.NUTRIENTS_SITUATION_USER_APPLY);
    		if(!StringUtils.isEmpty(isCancel) && isCancel.equals("0")){
    			updateMap.put("dealState", "cancel");
    			updateMap.remove("userAmount");
    			updateMap.remove("actualAmount");
    		}
    		updateMap.put("updateTime",currenTime);
    		updateMap.put("updateAuthor",situation.getUserId());
    		iNutritionSchemeUsedDao.updateSituationAmount(updateMap);
    	}else{
    		//查询部分参数
    		SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd");
    		PtCourseSituation ptCourseSituation = new PtCourseSituation();
    		//查询当前正在使用的疗程
    		Map<String,Object> param = new HashMap<String,Object>();
    		param.put("userId", userId);
    		//查询当前开始的疗程   没有则直接返回
    		param.put("tenantId", tenantId);
    		param.put("status",Constants.COMMON_STATUS_NOMAL);
    		param.put("statusEable",Constants.COMMON_STATUS_ENABLE);
    		Map<String,Object> courseMap = new HashMap<String,Object>();
    		courseMap = iNutritionSchemeUsedDao.selectCurrentCourse(param);
    		if(courseMap==null || courseMap.isEmpty()){
    			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"该时间段不存在食谱");
    		}
    		ptCourseSituation.setPcourseId((String)courseMap.get("ptCourseId"));
    		ptCourseSituation.setPschemeId((String)courseMap.get("ptSchemeId"));
    		ptCourseSituation.setDay(DateTimeUtil.daysBetweenDate(DateTimeUtil.parseDate(courseMap.get("firstTime")+"", DateTimeUtil.yyyy_MM_dd), new Date())+1);
    		//新添加的食物
    		String id = SeqUtil.getSeqNo();
    		rspMap.put("situationId", id);
			ptCourseSituation.setId(id);
			ptCourseSituation.setCreateTime(currenTime);
			ptCourseSituation.setFoodId(foodId);
			ptCourseSituation.setStatus(Constants.COMMON_STATUS_NOMAL);
			ptCourseSituation.setUserId(userId);
			ptCourseSituation.setTenantId(tenantId);
			ptCourseSituation.setTime(df.parse(time));
			ptCourseSituation.setPeriodId(periodId);
			ptCourseSituation.setDealState(Constants.NUTRIENTS_SITUATION_USER_APPLY);
			ptCourseSituation.setUserAmount(Float.parseFloat(total));
			ptCourseSituation.setActualAmount(Float.parseFloat(total));
			ptCourseSituation.setDefaultAmount(Float.parseFloat(total));
			ptCourseSituation.setUpdateTime(currenTime);
			ptCourseSituation.setUpdateAuthor(userId);
			ptCourseSituationlist.add(ptCourseSituation);
    	}
        if(!CollectionUtils.isEmpty(ptCourseSituationlist)){
        	iNutritionSchemeUsedDao.saveNewPatientSituation(ptCourseSituationlist);
        }
        //保存修改记录--
		List<PtNtsituationModifyLog> insertList = new ArrayList<PtNtsituationModifyLog>();
		PtNtsituationModifyLog situationModifyLog = null;
		situationModifyLog =  new PtNtsituationModifyLog();
		situationModifyLog.setId(SeqUtil.getSeqNo());
		situationModifyLog.setCreateTime(currenTime);
		situationModifyLog.setActualAmount(Float.parseFloat(total));
		situationModifyLog.setRemark("用户上传数据");

		situationModifyLog.setType(Constants.NUTRIENTS_SITUATION_USER_APPLY);
		situationModifyLog.setModifyId(userId);
		situationModifyLog.setSituationId(situationId);
		situationModifyLog.setTenantId(tenantId);
		situationModifyLog.setModifyName("用户上传");
		insertList.add(situationModifyLog);
		if(!CollectionUtils.isEmpty(insertList)){
			iNutritionSchemeUsedDao.savePtNtsituationLog(insertList);
		}
		return rspMap;
	}
	/**
	 * 通过食物类别查询食物列表
	 */
	@Override
	public  Map<String,Object> listFoodByType(Map<String, Object> map) throws Exception{
		Map<String,Object> returnmap = new HashMap<String,Object>();
		List<Map<String,Object>> courseMap = iNutritionSchemeUsedDao.listFoodByType(map);
		int total = iNutritionSchemeUsedDao.countFoodByType(map);
		returnmap.put("list", courseMap);
		returnmap.put("total", total);
		return returnmap;
	}
	@Override
	public Map<String,Object> patientScheduleQry(Map<String, Object> map)throws Exception {
		//计划查询
		String userId = (String)map.get("userId");
		String queueId = (String)map.get("queueId");
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("userId", userId);
		param.put("id", queueId);
		String tenantId = "";

		//查询租户id
		FollowQueue queue = fllowQueueService.getQueueDetailByQueueId(param);
		if(null != queue){
			tenantId = queue.getTenantId();
		}
		//查询当前开始的疗程   没有则直接返回
		param.put("tenantId", tenantId);
		param.put("status",Constants.COMMON_STATUS_NOMAL);
		param.put("statusEable",Constants.COMMON_STATUS_ENABLE);
		Map<String,Object> courseMap = iNutritionSchemeUsedDao.selectCurrentCourse(param);

		Map<String,Object> rspMap = new HashMap<String,Object>();
		List<Map<String,Object>> periodList = null ;
		if(null != courseMap){
			String ptCourseId = (String)courseMap.get("ptCourseId");
			param.clear();
			param.put("ptCourseId",ptCourseId);
			periodList = iNutritionSchemeUsedDao.selectPatientPeriodList(param);

			//查询当天的营养推送计划
			param.put("currentTime",DateUtil.getCurrDate2());
			List<Map<String,Object>> situationList = iNutritionSchemeUsedDao.selectPatientSituation(param);
			if(!CollectionUtils.isEmpty(periodList)){
				for(int i = 0;i<periodList.size();i++){
					String key = (String)periodList.get(i).get("periodId");
					String startTime = ""; int start = (int)periodList.get(i).get("startTime");
					String endTime = ""; int end = (int)periodList.get(i).get("endTime");
					if(start > 0 && end >0){
						startTime = start / 60 +":"+start%60;
						endTime = end / 60 +":"+end%60;
					}
					periodList.get(i).put("startTime",startTime);
					periodList.get(i).put("endTime",endTime);

					List<Map<String,Object>> foodList = new ArrayList<Map<String,Object>>();
					for(int j = 0;j<situationList.size();j++){
						Map<String,Object> situationMap =  situationList.get(j);
						String periodId = (String)situationMap.get("periodId");
						if(key.equals(periodId)){
							Map<String,Object> food = new HashMap<String,Object>();
							//通过id查询食物的分类
							Map<String,Object> foodtype = iNutritionSchemeUsedDao.getFoodTypeByFoodId((String)situationMap.get("foodId"));
							food.put("foodTypeName",foodtype.get("foodTypeName"));
							food.put("foodTypeId",foodtype.get("foodTypeId"));

							food.put("foodName",situationMap.get("foodName"));
							food.put("foodId",situationMap.get("foodId"));
							food.put("fat",situationMap.get("fat"));
							food.put("pcourseId",situationMap.get("pcourseId"));//疗程id
							food.put("pschemeId",situationMap.get("pschemeId"));//方案id
							food.put("day",situationMap.get("DAY"));//方案id
							food.put("time",situationMap.get("TIME"));//方案id
							food.put("foodUnit",situationMap.get("foodUnit"));
							food.put("situationId",situationMap.get("situationId"));
							food.put("total",situationMap.get("defaultAmount"));
							if(null !=situationMap.get("dealState") &&
									(Constants.NUTRIENTS_SITUATION_USER_APPLY.equals(situationMap.get("dealState"))||
											Constants.NUTRIENTS_SITUATION_DOCTOR_SIGN.equals(situationMap.get("dealState")))){
								food.put("isComplete","1");
							}else{
								food.put("isComplete","0");
							}

							foodList.add(food);
						}
					}
					periodList.get(i).put("foodList",foodList);
				}
				rspMap.put("periodList",periodList);
			}

		}

		return rspMap;
	}

}
